package org.dreamwork.tools;

import java.security.SecureRandom;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.*;

public class LocalUtil {
    public static final ExecutorService service = Executors.newCachedThreadPool ();
    public static final ScheduledExecutorService scheduler =
        Executors.newSingleThreadScheduledExecutor ();
    public static final ResourceBundle ui = ResourceBundle.getBundle ("ui");
    
    public static boolean isEmpty (String text) {
        return text == null || text.trim ().length () == 0;
    }

    private static Map<Long, ScheduledFuture<?>> tasks = new ConcurrentHashMap<> ();
    private static SecureRandom SR;

    public static long schedule (Runnable task, long delay, TimeUnit unit) {
        long id = createId ();
        ScheduledFuture<?> future = scheduler.schedule (()->{
            try {
                task.run ();
            } finally {
                tasks.remove (id);
            }
        }, delay, unit);
        tasks.put (id, future);
        return id;
    }

    public static void cancelTask (long taskId) {
        ScheduledFuture<?> f = tasks.get (taskId);
        if (f != null && !f.isDone () && !f.isCancelled ()) {
            f.cancel (true);
        }
        tasks.remove (taskId);
    }

    private static long createId () {
        if (SR == null) {
            long now = System.currentTimeMillis ();
            byte[] seed = new byte[8];
            for (int i = 0; i < 8; i ++) {
                seed [i] = (byte) (now >> (8 * (7 - i)));
            }
            SR = new SecureRandom (seed);
        }

        return SR.nextLong ();
    }
}
